import {
	login,
	queryUserInfo
} from "@/api/login";
import {
	getTechList,
	getServersDict
} from "@/api/dict";

/**
 * 获取openid
 */
function getToken() {
	//获取用户
	return new Promise((resolv, reject) => {
		try {
			uni.login({
				success: async (loginRes) => {
					const token = await login({
						"code": loginRes.code,
					})
					uni.setStorageSync("token", token?.wx_token)
					resolv(token?.wx_token);
				}
			})
		} catch (e) {
			console.log(e)
			reject(e)
		}
	})
}

/**
 * 获取用户信息
 */
function getUserInfo() {
	return new Promise(async (resolv, reject) => {
		try {
			const res = await queryUserInfo()
			if (res.code === 200) {
				uni.setStorageSync("userInfo", res.data)
				resolv(res.data);
			} else if (res.code === 500) {
				uni.setStorageSync('userInfo', null)
			}
		} catch (e) {
			console.log(e)
			reject(e)
		}
	})
}

/**
 * 获取动态字典
 */
async function getDictInfo() {
	return new Promise(async (resolv, reject) => {
		try {
			let flagOK = false
			const dictInfo = {}
			const techRes = await getTechList()
			const techDict = {}
			const serversRes = await getServersDict()
			const serversDict = {}
			if (techRes?.rows) {
				techRes.rows.forEach(item => {
					techDict[item.dictValue] = item.dictLabel
				})
				dictInfo["techDict"] = techDict
			}
			if (serversRes?.rows) {
				serversRes?.rows.forEach(item => {
					serversDict[item.dictValue] = item.dictLabel
				})
				dictInfo["serversDict"] = serversDict
			}
			uni.setStorageSync("dictInfo", dictInfo)
			resolv(dictInfo);
		} catch (e) {
			console.log(e)
			reject(e)
		}
	})
}

export default {
	getToken: getToken,
	getUserInfo: getUserInfo,
	getDictInfo: getDictInfo
}